package com.qzsoft.zhjd.laboratory.modules.asphaltPenetrometer.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PenetrometerServer {
    private static final int PORT = 9164; // 监听的端口号针入度
//    private static final int PORT_SOFT = 9165; // 监听的端口号软化点
//    private static final int PORT = 9876; // 监听的端口号
    private static final Logger LOGGER = Logger.getLogger(PenetrometerServer.class.getName());
    private static final ExecutorService executorService = Executors.newFixedThreadPool(10); // 线程池大小
    private final AsphaltPenetrometerServiceImpl penetrometerService;

    public PenetrometerServer(AsphaltPenetrometerServiceImpl penetrometerService) {
        this.penetrometerService = penetrometerService;
    }

    public void startServer() {
        ServerSocket serverSocket = null;
        ServerSocket serverSocketSoft = null;

        try {
            serverSocket = new ServerSocket(PORT);
            LOGGER.info("服务器已启动，正在监听端口 " + PORT);
            System.out.println("服务器已启动，正在监听端口 " + PORT);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                LOGGER.info("客户端已连接: " + clientSocket.getInetAddress());
                System.out.println("客户端已连接: " + clientSocket.getInetAddress());
                // 使用线程池处理客户端请求
                executorService.submit(new ClientHandler(clientSocket, penetrometerService));
            }
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "服务器启动失败", e);
            System.out.println("服务器启动失败 " + e);
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    LOGGER.log(Level.SEVERE, "关闭服务器套接字失败", e);
                }
            }
            executorService.shutdown();
        }
    }

    static class ClientHandler implements Runnable {
        private final Socket clientSocket;
        private final AsphaltPenetrometerServiceImpl penetrometerService;

        public ClientHandler(Socket clientSocket, AsphaltPenetrometerServiceImpl penetrometerService) {
            this.clientSocket = clientSocket;
            this.penetrometerService = penetrometerService;
        }

        @Override
        public void run() {
            InputStream in = null;
            try {
                in = clientSocket.getInputStream();
                byte[] buffer = new byte[1024]; // 假设每次最多读取1024字节
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    byte[] receivedbyte = Arrays.copyOf(buffer, bytesRead);
                    String receivedData = bytesToHex(receivedbyte);
                    LOGGER.info("收到客户端消息: " + receivedData);
                    System.out.println("收到客户端消息: " + receivedData);
                    // 调用服务层的方法来处理数据
                    penetrometerService.parsingDataTwob(receivedData, "4f2adc7fe84e556ca43acea7674034ac");
                }
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, "处理客户端请求时发生错误", e);
            } finally {
                try {
                    if (in != null) in.close();
                    clientSocket.close();
                } catch (IOException e) {
                    LOGGER.log(Level.SEVERE, "关闭客户端套接字失败", e);
                }
            }
        }

        // 将字节数组转换为16进制字符串的方法
        private String bytesToHex(byte[] bytes) {
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                result.append(String.format("%02X ", b));
            }
            return result.toString().trim();
        }
    }
}
